package jsd2204.bookstore.bookserver.service.impl;

import jsd2204.bookstore.bookserver.ex.ServiceException;
import jsd2204.bookstore.bookserver.mapper.BookMapper;
import jsd2204.bookstore.bookserver.mapper.UserMapper;
import jsd2204.bookstore.bookserver.pojo.dto.ConsumeDTO;
import jsd2204.bookstore.bookserver.pojo.entity.User;
import jsd2204.bookstore.bookserver.service.UserService;
import jsd2204.bookstore.bookserver.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

/**
 * @author jiale
 * @version 1.0
 * @description这是关于用户的一个实现类
 * @date 2022/08/01 22:12
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    BookMapper bookMapper;

    public UserServiceImpl(){
        log.debug("创建业务对象:UserServiceImpl");
    }

    @Override
    public void buyBook(Double money,Long id,HttpSession session) {
        User user=(User) session.getAttribute("user");
        Long userId=user.getId();
        Double asset = assetById(userId);
        if(asset<money) {
            String message="余额不足";
            throw new ServiceException(ServiceCode.ERR_UPDATE,message);
        }
        asset-=money;
        ConsumeDTO consumeDTO=new ConsumeDTO();
        consumeDTO.setAsset(asset);
        consumeDTO.setId(userId);
        userMapper.buyBook(consumeDTO);
        bookMapper.salesBook(id);
    }

    @Override
    public Double assetById(Long id) {
        Double asset = userMapper.assetById(id);
        return asset;
    }
}
